import JSEncrypt from 'jsencrypt'
//签名密钥串(前后端要一致，正式发布请自行修改)
/**
 * @param {String} rsaPublicKey - 公钥
 * @param {String} rsaPrivateKey - 私钥
 * @param {Function} rsaEncrypt - 加密
 * @param {Function} rsaDecrypt - 解密
 */

export default class SignRSAUtils {
  static rsaPublicKey = `-----BEGIN PUBLIC KEY-----
  MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDeEjfUsqwC0xkcRtElpxB9bH6m
  KvPXOxHhB9Rt5BS540vOhaoxOblVW5kEZQv2L435Wf8YH8Qqo3zVCyFCJ2L9kJLW
  Q9XW9JM5KH18FeqsJUzQRYh8UoC4CJsadobKZ2ELpuU8mEwGKo/uzvsua8vJ87vW
  +N5TDyPVK+vIlMyLAQIDAQAB
  -----END PUBLIC KEY-----`

  static rsaPrivateKey = `-----BEGIN RSA PRIVATE KEY-----
  ...
   -----END RSA PRIVATE KEY-----`

  static Appkey = '9ED15CF418CB43BB'

  constructor() {}

  /**
   * json参数升序
   * @param jsonObj 发送参数
   */
  static sortAsc(jsonObj) {
    let objSort = {}
    Object.keys(jsonObj)
      .sort()
      .forEach((key) => {
        objSort[key] = jsonObj[key]
      })
    return objSort
  }

  /**
   * @description 加密
   * @param url 请求url链接
   * @returns {string} 获取签名
   */
  static rsaEncrypt(url) {
    const path = this.getUrlToPuth(url)
    const signObj = {
      url: path,
      key: SignRSAUtils.Appkey,
      timestamp: this.getTimestamp(),
    }
    const jsonObj = this.sortAsc(signObj)
    const jsonObjStr = JSON.stringify(jsonObj)
    // console.log('🚀 ~ SignRSAUtils ~ rsaEncrypt ~ jsonObjStr:', jsonObjStr)

    const _JSEncrypt = new JSEncrypt()
    _JSEncrypt.setPublicKey(SignRSAUtils.rsaPublicKey)

    const encrypted = _JSEncrypt.encrypt(jsonObjStr)
    // console.log('🚀 ~ signRSAUtils ~ rsaEncrypt ~ signStr:', encrypted)
    return encrypted
  }

  /**
   * @description 解密
   * @param str 解密数据
   * @returns {object} 解密结果
   */
  static rsaDecrypt(str) {
    const _JSEncrypt = new JSEncrypt()
    _JSEncrypt.setPublicKey(SignRSAUtils.rsaPrivateKey)

    const uncrypted = _JSEncrypt.decrypt(str)
    // console.log('🚀 ~ SignRSAUtils ~ rsaDecrypt ~ uncrypted:', uncrypted)
    return uncrypted
  }

  static getUrlToPuth(url) {
    const urlReg = /https?:\/\/[^\/]+(\/[^?#]*)/
    if (!urlReg.test(url)) return url.match(/(\/[^?#]*)/)[0]

    return url.match(urlReg)[1]
  }

  /**
   * 接口签名用 生成header中的时间戳
   * @returns {number}
   */
  static getTimestamp() {
    return new Date().getTime()
  }

  /**
   * @description 对象加密
   * @param {object} obj 请求url链接
   * @returns {string} 获取签名
   */
  static objRsaEncrypt(obj) {
    const jsonObj = this.sortAsc(obj)
    const jsonObjStr = JSON.stringify(jsonObj)

    const _JSEncrypt = new JSEncrypt()
    _JSEncrypt.setPublicKey(SignRSAUtils.rsaPublicKey)

    const encrypted = _JSEncrypt.encrypt(jsonObjStr)
    return encrypted
  }
}
